<form class="layui-form seller-form" action="">

    <div class="layui-form-item">

        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline" id="year_box">
                <select name="supply_index_year" lay-filter="supply_index_year" id="supply_index_year" list="year_list" lay-search>
                    <option value=""></option>
                    <datalist  id="year_list" lay-search>
                        {volist name="yearList" id="yearList"}
                        <option value="{$yearList.id}">{$yearList.year}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label>
            <div class="layui-input-inline" id="season_box">
                <select name="supply_index_season" lay-filter="supply_index_season" id="supply_index_season" list="season_list" lay-search>
                    <option value=""></option>
                    <datalist  id="season_list" lay-search>
                        {volist name="seasonList" id="seasonList"}
                        <option value="{$seasonList.season_id}">{$seasonList.season_name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部/院：</label>
            <div class="layui-input-inline" id="dep_box">
                <select name="dep_id" lay-filter="dep_id" id="dep_id" list="dep_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dep_list" lay-search>
                        {volist name="deptList" id="deptList"}
                        <option value="{$deptList.bmdm}">{$deptList.bmmc}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">专业：</label>
            <div class="layui-input-inline" id="specialty_box">
                <select name="specialty_id" lay-filter="specialty_id" id="specialty_id" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">班级：</label>
            <div class="layui-input-inline" id="class_box">
                <select name="class_id" lay-filter="class_id" id="class_id" list="class_list" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">方向：</label>
            <div class="layui-input-inline" id="dir_box">
                <select name="dir" lay-filter="dir" id="dir" list="dir_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dir_list" lay-search>
                        {volist name="dirList" id="dirList"}
                        <option value="{$dirList.id}">{$dirList.name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">状态：</label>
            <div class="layui-input-inline" id="is_dy_box">
                <select name="is_dy" lay-filter="is_dy" id="is_dy" lay-search>
                    <option value=""></option>
                    <option value="0">未打印</option>
                    <option value="1">已打印</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="search"><i class="iconfont icon-chaxun"></i>查询</button>
            <button type="button" id="supply_draw" class="layui-btn layui-btn-sm supply_draw"><i class="layui-icon">&#xe608;</i>教材补发</button>
            <button type="button" id="reset_print" class="layui-btn layui-btn-sm reset_print"><i class="layui-icon">&#xe66d;</i>重置打印状态</button>
            <button type="button" id="book_draw_print" class="layui-btn layui-btn-sm print"><i class="layui-icon">&#xe66d;</i>打印</button>
        </div>

    </div>

</form>

<div class="table-body">
    <table id="booksupplydrawTable" lay-filter="booksupplydrawTable"></table>
</div>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function () {
        var layer = layui.layer, table = layui.table, form = layui.form, date = layui.laydate;
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        var printstatus = 1;
        var printindex = 0;
        var myInterval = null;
        var checkedData = new Array();
        //执行渲染
        table.render({
            elem: '#booksupplydrawTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-165',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            id: 'booksupplydrawTable',
            url: "{:url('BookCommon/returnNull')}",
            // url: "{:url('BookDraw/booksupplydrawindex')}",
            cols: [[ //标题栏
                { type: 'checkbox' },
                { field: 'year', sort: true, title: '年度', width: 80, align: 'center' },
                { field: 'season', sort: true, title: '季度', width: 80, align: 'center' },
                { field: 'dep', sort: true, title: '部/院', width: 200, align: 'center' },
                { field: 'specialty', sort: true, title: '专业', width: 200, align: 'center' },
                { field: 'class', sort: true, title: '班级', width: 300, align: 'center' },
                { field: 'dir', sort: true, title: '方向', width: 80, align: 'center' },
                { field: 'num', sort: true, title: '数量', width: 80, align: 'center' },
                {
                    field: 'is_dy', title: '状态', width: 100, align: 'center', templet: function (data) {
                        html = '<div style="color: #009688;">未打印</div>';
                        html = (data.is_dy == 0) ? html : "已打印";
                        return html;
                    }
                },
                {
                    field: 'option', title: '操作', templet: function (d) {
                        var html = '<a class="layui-btn layui-btn-xs showdetail" data-id="' + d.id + '">查看明细</a>';
                        html += '<a class="layui-btn layui-btn-xs del layui-btn-danger" name="del" data-id="' + d.id + '">删除</a>'; 
                        return html;
                    }, align: 'center', width: 140
                }
            ]], //设置表头
            done: function(res, curr, count){
                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            }
        });

        // 查询
        form.on('submit(search)', function (data) {
            table.reload('booksupplydrawTable', {
                where: data.field,
                page: {curr: 1},
                url: "{:url('BookDraw/booksupplydrawindex')}",
            });
            return false;
        });

        //查看明细
        $(document).on('click', '.showdetail', function () {  
            // 打开一个查看发放明细的新页面
            var supplyid = $(this).attr('data-id');
            var url = "{:url('manage/BookDraw/booksupplydrawdetail')}" + '?supplyid=' + supplyid;
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage(url, '教材补发明细'); 
            return false;  
        });
 
        //删除记录
        $(document).on('click', '.del', function () { 
            var supplyid = $(this).attr('data-id');
            layer.confirm('您确定删除此补发记录吗？', {
                btn: ['确认', '取消'], //按钮
            }, function () {
                JsPost("{:url('BookDraw/booksupplydrawdel')}", {supplyid:supplyid}, function (res) {             
                    //删除逻辑中判断只有一条数据时应该刷新前一页信息
                    layer.msg(res.msg);
                    if(res.status){
                        if(dataNum == 1){
                            currPage = currPage - 1;
                        }

                        table.reload('booksupplydrawTable', {
                            page: {
                                curr: currPage
                            }
                        });
                        return false;
                    }
                });
            }, function () {
                $("a[name='del']").removeClass("layui-btn-disabled");
                $("a[name='del']").removeAttr("disabled");
                layer.close(1);
            });
        }); 

        // 修改保存
        form.on('submit(draw-edit)',function(data){
            var num = data.field.num;
            if(parseInt(num) != num){
                layer.msg('数量必须是整数！', {time: 1300});
                return false;
            }
            if(num<=0){
                layer.msg('数量必须大于0！', {time: 1300});
                return false;
            }
            $("#edit-save-btn").addClass("layui-btn-disabled");
            $('#edit-save-btn').attr("disabled", true);

            JsPost("{:url('BookDraw/booksupplydrawedit')}", data.field, function(res){
                if(res.status){
                    layer.close(window.box);
                    layer.msg(res.msg,{time:1300},function(){
                        table.reload('booksupplydrawTable');
                    });
                }else{
                    $("#edit-save-btn").removeClass("layui-btn-disabled");
                    $('#edit-save-btn').removeAttr("disabled");

                    layer.msg(res.msg,{time:1300});
                }
            })
        });
  
        layui.use('form', function () {
            // 联动年度
            form.on('select(supply_index_year)', function (data) {
                getClass(data);
            });

            // 联动专业  
            form.on('select(specialty_id)', function (data) {
                getClass(data);
            });

            // 联动部门
            form.on('select(dep_id)', function (data) {
                getSpecialty(data);
            });
        });

        // 得到专业
        function getSpecialty(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getSpecicalties')}",
                data: 'bmdm=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#specialty_id").empty();//清空下拉框的值
                        $('#specialty_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#specialty_id').append(new Option(item.zymc, item.zydm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 得到班级
        function getClass(data) { 
            var dept = $("#dep_id").val();
            var specialty_id = $("#specialty_id").val();
            var year = $("#supply_index_year").val();
            var season = $("#supply_index_season").val();

            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getClasses')}",
                data: {
                        "bmdm": dept,
                        "zydm": specialty_id,
                        "plan_year":  year,
                        "plan_season": season
                    },
                success: function(e) {
                    if(e.status) {
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#class_id').append(new Option(item.plan_class_name, item.plan_class_id));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };

        // 教材补发
        $(document).on('click','.supply_draw',function(){
            var url = "{:url('manage/BookDraw/supplydrawsave')}";
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage(url, '教材补发（新增）'); 
            return false;        
        });

        // 重置打印状态
        $(document).on('click', '.reset_print', function(){
            let checkStatus = table.checkStatus('booksupplydrawTable');
            data = checkStatus.data;

            if(data.length==0){
                layer.msg('请先选择要重置打印状态的数据行！', { time: 1300 });
                return false;
            }

            let ids = "";
            let flag = true;
            $.each(data, function(index, item){
                if(item.is_dy==0){
                    layer.msg('已处于未打印状态的不需要重置，请重新选择！', { time: 1300 });
                    flag = false;
                    return false;
                }
                ids += item.id + ",";
            })
            
            if(flag){
                $('#reset_print').addClass("layui-btn-disabled");
                $('#reset_print').attr("disabled", true);
                ids = ids.substring(0, ids.length - 1);
                resetPrintStatus(ids);
                $('#reset_print').removeClass("layui-btn-disabled");
                $('#reset_print').removeAttr("disabled"); 
            }
        });

        // 重置打印状态：方法
        function resetPrintStatus(ids){
            layer.confirm('确定要重置吗?', {icon: 3, title:'提示'}, function(){
                JsPost("{:url('BookDraw/booksupplyresetprintstatus')}", {ids:ids}, function (res) {
                    if(res.status){
                        layui.table.reload('booksupplydrawTable', {
                            // where: data.field, 
                            page: {curr: 1},
                            url: "{:url('BookDraw/booksupplydrawindex')}",
                        });
                    } 
                    layer.msg(res.msg);
                });
            });
        }

        // 打印状态检查
        function printTimer() {
            if(printstatus == 1) { 
                printstatus = 0;
                printBookDrawInfo(checkedData[printindex]);
                printindex++;
            }

            if (printindex == checkedData.length) {
                window.clearInterval(myInterval);
                checkedData = new Array();
                myInterval = null;
                printindex = 0;
                printstatus = 1;
            }
        }

        // 打印
        $(document).on('click','.print',function(){
            var checkStatus = table.checkStatus('booksupplydrawTable');
            checkedData = checkStatus.data;

            if(checkedData.length==0){
                layer.msg('请先选择要打印的数据行！', { time: 1300 });
                return false;
            }

            let ids = "";
            let flag = true;
            $.each(checkedData, function(index, item){
                if(item.is_dy==1){
                    layer.msg('处于已打印状态的不能再次打印，请重新选择！', { time: 1300 });
                    flag = false;
                    return false;
                }
                ids += item.id + ",";
            })

            if(flag){
                $('#book_draw_print').addClass("layui-btn-disabled");
                $('#book_draw_print').attr("disabled", true);

                myInterval = setInterval(function(){ printTimer() }, 1000);

                // 修改打印状态，刷新页面
                ids = ids.substring(0, ids.length - 1);
                changePrintStatus(ids);
                $('#book_draw_print').removeClass("layui-btn-disabled");
                $('#book_draw_print').removeAttr("disabled");
            }
        });
    
        // 打印函数
        function printBookDrawInfo(bookDrawInfo) {
            // 获取打印信息
            JsGet("{:url('BookPlan/getBookInfoBySupplyDrawId')}?id="+bookDrawInfo['id'], function (res) {
                if(res.status){
                    // 构造打印数据
                    var ip = '127.0.0.1';
                    var port = '12345';

                    if(ip==""||port==""){ 
                        layer.msg("ip,port不能为空", { time: 1300 }); 
                        return false;
                    }
                    
                    var msg = '{'
                        +'"method":"' + 'printreport' +'"'
                        +',"ReportType":"' + 'gridreport' +'"'  /*报表类型 gridreport fastreport reportmachine 为空 将默认为gridreport  */
                        +',"ReportName":"' + 'supplybookdraw.grf' +'"' /*报表文件名 测试报表 */

                        +',"ReportVersion":"' + '1' +'"' /*可选。报表版本, 为空则默认1  如果本地报表的版本过低 将从 ReportUrl 地址进行下载更新*/
                        +',"ReportUrl":"' + '' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        //+',"ReportUrl":"' + 'http://localhost/test.grf' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        +',"Copies":"' + '1' +'"' /*可选。打印份数，支持指定打印份数。默认1份,如果为零,不打印,只返回报表生成的pdf,jpg等文件*/
                        
                        +',"Duplex":"' + '0' +'"' /*可选。双面打印 默认 0 需要双面打印的时候,请设置 2 或者3 , 可设置 0 打印机默认 1 单页 2 水平 3 垂直*/
                        
                        //+',"PrinterName":"' + $("#PrinterS option:selected").text() +'"' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrinterName":""' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrintOffsetX":"' + '0' +'"' /*可选。打印右偏移，单位厘米。报表的水平方向上的偏移量，向右为正，向左为负。*/
                        +',"PrintOffsetY":"' + '0' +'"' /*可选。打印下偏移，单位厘米。 报表的垂直方向上的偏移量，向下为正，向上为负。*/
                        +',"supplyview":"' + '0' +'"'  /*可选。是否预览，和主界面设置的效果一样 为空默认不预览,   0：不预览，1：预览(弹出导出的pdf,jpg等文件)。*/
                        +',"token":"' + 'aa' +'"' /*可选。只要token值在列表中 方可打印*/
                        +',"taskId":"' + '1234567' +'"' /*可选。多个打印任务同时打印时，根据该id确定返回的是哪个打印任务。 */
                        +',"exportfilename":"' + '' +'"'  /*可选。自定义 导出 文件名称 为空 或者 自定义名称 如 test */
                        +',"exportfiletype":"' + '' +'"'  /*可选。自定义 导出 文件格式 为空 或者 自定义名称 如 pdf  */

                        +',"Control": ['  ///*部件框，可选值：AsStaticBox ,AsMemoBox,AsRichTextBox,AsPictureBox (url或base64格式),AsBarcode*/
                                //静态框 AsStaticBox  综合文字框 AsMemoBox, RTF文本框 AsRichTextBox,图像框 AsPictureBox (url或base64格式), 条码二维码 AsBarcode*
                                            
                                +'{"type": "AsStaticBox", "name": "dep","value": "'+bookDrawInfo['dep']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "dir","value": "'+bookDrawInfo['dir']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "class","value": "'+bookDrawInfo['class']+'","required": false},'
                            +']'
                        
                        +',"Field": ['  ///*字段， type ftBlob (base64格式) ,ftString ftInteger ftBoolean, ftFloat, ftCurrency,ftDateTime,  size (ftString 设置为实际长度,其他的设置为0,例如 ftInteger ftBlob 等设置为0 ) 
                                
                                +'{"type": "ftString", "name": "xuhao","size": 255,"required": true},'
                                +'{"type": "ftString", "name": "jiaocai","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "chubanshe","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "ISBN","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "shuliang","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "danjia","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "jine","size": 255,"required": false},' 
                                +'{"type": "ftString", "name": "beizhu","size": 255,"required": false},' 

                            +']'

                        +',"Data": [';  ///*数据行

                            $.each(res.data, function(index, item){
                                msg += '{"xuhao": "'+item['xuhao']+'", "jiaocai": "'+item['jiaocai']+'","chubanshe": "'+item['chubanshe']+'", "ISBN": "'+item['ISBN']+'", "shuliang": "'+item['shuliang']+'", "danjia": "'+item['danjia']+'","jine": "'+item['jine']+'","beizhu": "'+item['beizhu']+'"},'
                            })

                            msg +=']'
                            
                        msg += '}';
                    
                    jQuery.support.cors = true;
                    $.ajax({
                        async : false,
                        url : "http://"+ip+":"+port+"/",
                        type : "POST",
                        contentType: "application/x-www-form-urlencoded", //要这样设置  
                        dataType : "json",
                        crossDomain: true,
                        data : msg,
                        beforeSend: function (XMLHttsupplyquest) {
                        },
                        success: function(data){		
                            if(data.status=="ok"){
                                printstatus = 1;
                                layer.msg("打印成功:"+data.data, { time: 1300 }); 
                                // 添加打印日志
                                printLog = {
                                    "func_type": 2
                                    ,"func_id": bookDrawInfo['id']
                                    ,"operator": {$userId}
                                    ,"content": "教材补发"};
                                addPrintLog(printLog);
                            }else{
                                printstatus = 1;
                                layer.msg("打印失败:"+data.data, { time: 1300 });
                            }
                        },
                        error: function(data){
                            layer.msg("连接HttpPrinter失败:"+JSON.stringify(data), { time: 1300 });
                        }
                    });
                }
            })
        }
        // 修改打印状态，刷新页面
        function changePrintStatus(ids){
            JsPost("{:url('BookDraw/booksupplyprintstatus')}", {ids:ids}, function (res) {
                if(res.status){
                    layui.table.reload('booksupplydrawTable', {
                        // where: data.field, 
                        page: {curr: 1},
                        url: "{:url('BookDraw/booksupplydrawindex')}",
                    });
                } 
                layer.msg(res.msg);
            });
        }
    })

    // 添加打印日志
    function addPrintLog(data){
        JsPost("{:url('BookCommon/addPrintLog')}", data, function (res) {
            if(res.status){
            } else{
            }
            // layer.msg(res.msg);
        });
    }
    $("#supply_index_year").val({$year});  // 年度：
    $("#supply_index_season").val({$season});  // 季度：
    $("#dir").val(1);  // 默认方向：就业
    $("#is_dy").val(0);  // 默认状态：未打印
</script>